#!/usr/bin/env python3

import os
import re
import sys

if len(sys.argv) < 2:
   print("error: too few arguments", file=sys.stderr)
         
path = sys.argv[2]

def lookup_regex(fname, pat1, pat2=None):
   fname = fname.replace("\_", "_")
   p1 = re.compile(pat1)
   if pat2 != None:
      p2 = re.compile(pat2)
   else:
      p2 = None
   cnt = 1
   i = None
   j = None
   p = p1
   try:
      with open(path+'/'+fname) as f:  
         line = f.readline()
         while line:
            m = p.search(line)
            if m != None:
               if p2 == None:
                  return (cnt, None)
               else:
                  if i == None:
                     i = cnt
                     p = p2
                  else:
                     j = cnt
                     return (i, j)
            cnt += 1
            line = f.readline()
         if i == None:
            print("%s: cannot find pat %s" % (fname, p1), file=sys.stderr)
         else:
            print("%s: cannot find pat %s" % (fname, p2), file=sys.stderr)
         return (None, None)
   except IOError:
      print("error: cannot open %s" % fname, file=sys.stderr)
      return (None, None)
   
def lineref(l):
   # file:/pattern/delta
   p = re.compile(r'\\lineref{(.*):\/(.*)\/([+-]?\d+)?}')
   m = p.search(l)
   if m != None:
      f = m.groups()[0]
      (i, j) = lookup_regex(f, m.groups()[1])
      delta = 0
      if m.groups()[2] != None:
         delta = int(m.groups()[2])
      if i != None:
         l = p.sub(r'\\lineref{%s}{%s}' % (f,str(i+delta)), l)
         print(l, end="")
      return
   # file:/line/
   p = re.compile(r'\\lineref\{(.*):(\d+)\}')
   m = p.search(l)
   if m != None:
      f = m.groups()[0]
      n = m.groups()[1]
      l = p.sub(r'\\lineref{%s}{%s}' % (f, n), l)
      print(l, end="")
      return
   # file:/pattern/delta,pattern/delta
   p = re.compile(r'\\linerefs{(.*):\/(.*)\/([+-]?\d+)?,\/(.*)\/([+-]?\d+)?}')
   m = p.search(l)
   if m != None:
      f = m.groups()[0]
      (i, j) = lookup_regex(f, m.groups()[1], m.groups()[3])
      delta1 = 0
      if m.groups()[2] != None:
         delta1 = int(m.groups()[2])
      delta2 = 0
      if m.groups()[4] != None:
         delta2 = int(m.groups()[4])
      if i != None and j != None:
         l = p.sub(r'\\linerefs{%s}{%s}{%s}' % (f, str(i+delta1), str(j+delta2)), l)
         print(l, end="")
      return
   print(l, end="")

with open(sys.argv[1]) as f:  
   line = f.readline()
   while line:
      lineref(line)
      line = f.readline()
